//
//  AddressListViewController.m
//  Exchange
//
//  Created by 张庆勇 on 2018/8/6.
//  Copyright © 2018年 张庆勇. All rights reserved.
//

#import "AddressListViewController.h"
#import "AddressCell.h"
#import "AddressModle.h"
#import "AddAddressViewController.h"
@interface AddressListViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong)NSMutableArray * dataAry;
@property (nonatomic,strong)UITableView * tableView;
@property (assign, nonatomic) NSUInteger         pages;
@property (nonatomic,strong)UIButton * addBut;
@property (nonatomic,strong) NoNetworkView * workView;
@end

@implementation AddressListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = [NSString stringWithFormat:@"%@%@",_modle.name,Localized(@"address")];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.addBut];
    // 上拉加载
    WeakSelf
    EXRefrechHeader *header = [EXRefrechHeader headerWithRefreshingBlock:^{
        weakSelf.pages = 0;
        
        [weakSelf getAddreasslist];
        
    }];
    [header beginRefreshing];
    self.tableView.mj_header = header;
    EXRefrechFootview *fooder = [EXRefrechFootview footerWithRefreshingBlock:^{
        weakSelf.pages++;
        [weakSelf getAddreasslist];
    }];
    self.tableView.mj_footer = fooder;
}
- (void)getAddreasslist
{
    WeakSelf
    [weakSelf GETWithHost:@"" path:withdrawAddress param:@{@"asset":_modle.name,@"offset":@(weakSelf.pages*10),@"limit":@(10)} cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView.mj_footer endRefreshing];
        if ([responseObject[@"code"] integerValue]==0)//成功
        {
            
            NSArray *list = responseObject[@"result"][@"records"];
            if (weakSelf.pages > 0)
            {
                [weakSelf.dataAry addObjectsFromArray:[AddressModle mj_objectArrayWithKeyValuesArray:list]];
                if (list.count<10)
                {
                    [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                }
                
            }else
            {
                weakSelf.dataAry = [AddressModle mj_objectArrayWithKeyValuesArray:list];
                if (list.count<10) {
                    [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                }
                
            }
            [self placeholderViewWithFrame:weakSelf.tableView.frame NoNetwork:NO];
            [weakSelf.tableView reloadData];
        }else
        {
            [weakSelf axcBasePopUpWarningAlertViewWithMessage:responseObject[@"message"] view:kWindow];
        }
    } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [weakSelf placeholderViewWithFrame:weakSelf.tableView.frame NoNetwork:YES];
    }];
}
- (void)placeholderViewWithFrame:(CGRect)frame NoNetwork:(BOOL)NoNetwork
{
    WeakSelf
    if (_dataAry.count == 0)
    {
        [_workView removeFromSuperview];
        _workView = [[NoNetworkView alloc] initWithFrame:_tableView.frame NoNetwork:NoNetwork];
        if (NoNetwork) {
            _workView.buttonclickeBlock = ^(UIButton *button) { //重新加载
                [weakSelf getAddreasslist];
            };
        }
        
        [_tableView addSubview:_workView];
    }else
    {
        [_workView dissmiss];
    }
    
}
#pragma  mark -----懒加载
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, UIScreenWidth, UIScreenHeight - kStatusBarAndNavigationBarHeight- RealValue_W(152))];
        _tableView.tableFooterView = [UIView new];
        _tableView.separatorColor = CELLCOLOR;
        _tableView.backgroundColor = TABLEVIEWLCOLOR;
        _tableView.delegate = self;
        _tableView.dataSource=self;
        _tableView.showsVerticalScrollIndicator = NO;
        [_tableView registerClass:[AddressCell class] forCellReuseIdentifier:@"AddressCell"];
    }
    return _tableView;
}
- (UIButton *)addBut
{
    WeakSelf
    if (!_addBut) {
        _addBut = [UIButton dd_buttonCustomButtonWithFrame:CGRectMake(RealValue_W(20), UIScreenHeight - RealValue_W(152) - kStatusBarAndNavigationBarHeight, UIScreenWidth- RealValue_W(40), RealValue_W(80)) title:Localized(@"Asset_Add_the_address") backgroundColor:TABTITLECOLOR titleColor:WHITECOLOR tapAction:^(UIButton *button) {
            AddAddressViewController * AddAddressVC = [[AddAddressViewController alloc] init];
            AddAddressVC.title = Localized(@"Asset_Add_the_address");
            AddAddressVC.modle = weakSelf.modle;
            [weakSelf.navigationController pushViewController:AddAddressVC animated:YES];
            AddAddressVC.addRelastblock = ^(BOOL isAddSuccess) {
                if (isAddSuccess) {
                    weakSelf.pages = 0;
                    [weakSelf getAddreasslist];
                }
            };
        }];
        KViewRadius(_addBut, 2);
    }
    return _addBut;
}
- (NSMutableArray *)dataAry
{
    if (!_dataAry) {
        _dataAry = [[NSMutableArray alloc]init];
    }
    return _dataAry;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
     AddressModle * modle = self.dataAry[indexPath.row];
    NSArray * array = [modle.address componentsSeparatedByString:@":"];
    if (array.count>1)
    {
        if (![NSString isEmptyString:array[1]])
        {
            return RealValue_H(226);
            
        }else
        {
            return RealValue_H(176);
        }
      
        
    }else
    {
      return RealValue_H(176);
    }
    
   
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataAry.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AddressCell *cell = [_tableView dequeueReusableCellWithIdentifier:@"AddressCell"];
    cell.modle=_dataAry[indexPath.row];
    WeakSelf
    [cell.copyAddressBtn add_BtnClickHandler:^(NSInteger tag) {
        AddressModle * modle = weakSelf.dataAry[indexPath.row];
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        pasteboard.string = modle.address;
        [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"Copy_to_paste") view:self.view];
    }];
    return cell;
}
//先要设Cell可编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
//定义编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}
//修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return Localized(@"address_delete");
}
//设置进入编辑状态时，Cell不会缩进
- (BOOL)tableView: (UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath {
    return NO;
}
// 自定义左滑显示编辑按钮
-(NSArray<UITableViewRowAction*>*)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    UITableViewRowAction *rowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault
                                                                         title:Localized(@"address_delete") handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath)
    {
        //在这里实现删除操作
        WeakSelf
        AddressModle * modle = self.dataAry[indexPath.row];
        
        [self POSTWithHost:@"" path:deleteWithdrawAddress param:@{@"id":modle.ID} cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            if ([responseObject[@"errorNo"] integerValue]==0)
            {
                //删除数据，和删除动画
                [weakSelf.dataAry removeObjectAtIndex:indexPath.row];
                [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:indexPath.row inSection:0]] withRowAnimation:UITableViewRowAnimationTop];
                [self axcBasePopUpWarningAlertViewWithMessage:responseObject[@"errorMsg"] view:kWindow];
            }else
            {
                
                [self axcBasePopUpWarningAlertViewWithMessage:responseObject[@"errorMsg"] view:kWindow];
            }
            
            
        } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        }];
                                                                             
    }];
    
    rowAction.backgroundColor = TABTITLECOLOR;
    NSArray *arr = @[rowAction];
    return arr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
